package com.qf.dao.impl;


import com.qf.dao.CartDao;
import com.qf.pojo.TbCart;
import com.qf.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Create by 周志豪 on 2022/8/21  10:48
 *
 * @authoe 周志豪
 * @veision 1.0
 * //TODO  想好了再去做
 * @since 1.0
 */

public class CartDaoImpl implements CartDao {

    @Override
    public TbCart findByUserIdAndGoodId(Long userId, Long goodId) {
        QueryRunner runner = DbUtils.getRunner();
        String sql = "SELECT * from tb_cart where id =? and pid=?";
        TbCart cart = null;
        try {
            cart = runner.query(sql, new BeanHandler<>(TbCart.class), userId, goodId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return cart;
    }

    @Override
    public int updateCount(Long userId, Long goodId, int num) {
        QueryRunner runner = DbUtils.getRunner();
        String sql = "UPDATE tb_cart set num =num+? where id =? and pid=?";
        try {
            return runner.update(sql, num, userId, goodId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int addCart(Long userId, Long goodId, int num) {
        QueryRunner runner = DbUtils.getRunner();
        String sql = "INSERT into tb_cart values (?,?,?,null)";
        try {
            int update = runner.update(sql, userId, goodId, num);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<TbCart> findByUserId(Long userId) {
        QueryRunner runner = DbUtils.getRunner();
        String sql = "SELECT pid,num from tb_cart where id=?";
        try {
            //查询某个用户的购物车数据
            List<TbCart> cartList = runner.query(sql, new BeanListHandler<>(TbCart.class), userId);
            return cartList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clearCart(Long userId) {
        QueryRunner runner = DbUtils.getRunner();

        //根据用户id删除所有的购物车数据
        String sql = "delete from tb_cart where id =?";
        try {
            int update = runner.update(sql, userId);
        } catch (SQLException e) {
           // throw new RuntimeException(e);
            e.printStackTrace();
        }
    }
}
